<template>
  <div class="setting-flow event-setting-flow">
    <!-- 头部 -->
    <flow-header
      :service-event-type-config="serviceEventTypeConfig"
      :setting-step="settingStep"
      :curr-tab.sync="currTab"
      :pending="pending"
      @checkModified="checkModified"
      @submit="submit"
    ></flow-header>

    <!-- 主体 -->
    <keep-alive>
      <component
        ref="comp"
        :is="settingStep[currTab].compName"
        :service-event-type-id="serviceEventTypeId"
        :eventTypeName="eventTypeName"
        @init="initialize"
      ></component>
    </keep-alive>
  </div>
</template>

<script>
// components
import FlowHeader from './components/FlowHeader.vue';
import FlowSettingPanel from './steps/FlowSettingPanel.vue';
import OtherSettingPanel from './steps/OtherSettingPanel.vue';
import CardSettingPanel from './steps/CardSettingPanel.vue';
// api
import { getEventTypeData, saveEventTypeProcess } from '@src/api/SettingServiceEventApi';
// utils
import { parse } from '@src/util/querystring';
import { cloneDeep, isEqual } from 'lodash';
import { SETTING_STEP } from '../../constant';
import { convertServiceEventConfig, saveEventConfigParams } from '../utils/conversionEventConfigUtils';
import ServiceEventConfig from './models/ServiceEventConfig';
import { getRootWindowInitData } from '@src/util/window'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* version control mixin */
import { VersionControlEventMixin } from '@src/mixins/versionControlMixin'

import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'

const { languagesList } = useFormMultiLanguage()

export default {
  name: 'service-event-flow',
  mixins: [VersionControlEventMixin],
  provide() {
    return {
      flowData: this.$data,
    };
  },
  data() {
    return {
      serviceEventTypeId: '',
      serviceEventTypeConfig: new ServiceEventConfig(),
      initServiceEventTypeConfig: {},
      currTab: 0,
      pending: false,
    };
  },
  computed: {
    eventTypeName() {
      return this.serviceEventTypeConfig?.name || ''
    },
    settingStep() {
      return SETTING_STEP;
    },
    // 灰度满意度方案
    customerSatisfaction() {
      return getRootWindowInitData()?.customerSatisfaction || false 
    }
  },
  mounted() {
    let query = parse(window.location.search) || {};
    this.serviceEventTypeId = query.serviceEventTypeId;

    if (this.serviceEventTypeId) {
      this.initPageData();
    }
    this.$eventBus.$on('event_type_update_config', this.submit);
  },
  methods: {
    async initialize() {
      try {
        if (this.serviceEventTypeId) {
          await this.initPageData()
          this.$refs.comp.updateEventCard();
        }
      }catch (error) {
        console.log(error)
      }
    },
    /** 初始化设置数据*/    
    async initPageData() {
      try {
        let { status, message, data } = await getEventTypeData({
          id: this.serviceEventTypeId,
        });
        if(status !== 0) return this.$message.warning(message);
        // 标题多语言兼容老数据
        if(!data.nameLanguage){
          data = this.compatibilityNameLanguage(data)
        }
        // 转化获取到的结果
        this.serviceEventTypeConfig = convertServiceEventConfig(data);
        // 备份初始化的值
        this.initServiceEventTypeConfig = cloneDeep(this.serviceEventTypeConfig);
      
      } catch (error) {
        console.error('事件类型数据获取失败', error);
      }
    },
    /** todo 检验页面修改*/
    async checkModified(callback, isReturn = false) {
      let isModified = !isEqual(this.serviceEventTypeConfig, this.initServiceEventTypeConfig);
      
      if (isModified) {
        let confirmData = {
          content: isReturn
            ? this.$t('event.setting.serviceEventTypeSetting.flow.tips1')
            : this.$t('event.setting.serviceEventTypeSetting.flow.tips2'),
          confirmText: isReturn ? this.$t('common.base.leave') : this.$t('common.base.save'),
          cancelText: isReturn ? this.$t('common.base.cancel') : this.$t('common.base.notSaveForNow'),
        };

        this.$confirm(confirmData.content, '', {
          confirmButtonText: confirmData.confirmText,
          cancelButtonText: confirmData.cancelText,
          type: 'warning',
          showClose: false,
          closeOnClickModal: false,
        })
          .then(async () => {
            //  保存[提交数据],进入下一页/离开[不提交数据]
            if (!isReturn) await this.submit();
            callback();
          })
          .catch(() => {
            //  取消操作: 返回[不保存], 切换 stepTab[暂存]
            //  TODO: * 待确认的是暂存后, 在退出当前页面前无法恢复之前数据
            if (isReturn) return;
            //  暂不保存[缓存不提交], 进入下一页
            if (!isReturn) {
              this.serviceEventTypeConfig = cloneDeep(this.initServiceEventTypeConfig);
            }
            callback();
          });
      } else {
        callback();
      }
    },
    /** 保存流程设置*/
    async submit(flag = false) {
      try {
      //  验证名称和颜色是否符合要求
        let isCheckName = this.checkoutName(this.serviceEventTypeConfig.name);
        if (!isCheckName) return;

        this.pending = true;

        if (this.currTab == 2) {
          return await this.$refs.comp.submit(flag);
        }

        // 客户满意度问卷方案设置必填
        let flowSetting = this.serviceEventTypeConfig.flowSetting || {};
        let satisfactionId = flowSetting?.evaluate?.questionId;
        if (this.customerSatisfaction && flowSetting.evaluate.state && !satisfactionId) {
          return this.$platform.notification({
            title: this.$t('event.setting.serviceEventTypeSetting.flow.tips3'),
            type: 'error'
          });
        }

        //  处理提交数据
        const submitParams = saveEventConfigParams(this.serviceEventTypeConfig);

        const { status, message, data } = await saveEventTypeProcess(submitParams);
        if(status !== 0 ) return this.$platform.notification({ type: 'error', title:this.$t('common.base.toast'), message });
  
        this.$platform.notification({
          title: this.$t('common.base.tip.saveSuccess'),
          type: 'success'
        })

        // 备份初始化的值
        this.initServiceEventTypeConfig = cloneDeep(this.serviceEventTypeConfig);
      } catch (error) {
        console.error(error);
      } finally {
        this.pending = false;
      }
    },
    /** 转化服务事件设置数据为接口所需数据*/
    config2Params(serviceEventConifg) {
      return serviceEventConifg;
    },
    /** 检验服务事件类型名称是否符合*/
    checkoutName(name) {
      let notificationTitle = '';
      if (!name) notificationTitle = this.$t('event.setting.serviceEventTypeSetting.flow.tips4');
      if (name.length > 100) notificationTitle = this.$t('common.validate.maxLen', {limit: '100'});
      // if (name && !/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(name))
      //   notificationTitle = this.$t('event.setting.serviceEventTypeSetting.flow.tips6');

      if (notificationTitle) {
        this.$platform.notification({
          title: notificationTitle,
          type: 'error',
        });
        return false;
      } 
      return true;
      
    },
    // 返回
    goBack() {
      let fromId = window.frameElement.getAttribute('fromid');
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      // this.$platform.openTab({
      //   id: 'M_SYSTEM',
      //   title: '事件流程设置',
      //   url: '/setting/serviceStation/eventType',
      //   reload: true,
      //   close: true,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceStation,
        titleKey: this.$t('event.setting.serviceEventTypeSetting.flow.tips7'),
        reload: true,
        fromId
      })
    },
    // 兼容多语言 namelanguage字段老数据
    compatibilityNameLanguage(data){
      data.nameLanguage = {}
      let keys = languagesList.map(v=>v.language)
      keys.map(key=>{
        data.nameLanguage[key] = ''
      })
      data.nameLanguage['zh'] = data.name
      return data
    }
  },
  beforeDestroy() {
    this.$eventBus.$off('event_type_update_config', this.submit);
  },
  components: {
    [FlowHeader.name]:FlowHeader,
    FlowSettingPanel,
    OtherSettingPanel,
    CardSettingPanel,
  },
};
</script>

<style lang="scss" scoped>
.setting-flow {
  min-width: 1080px;
}
</style>
<style lang="scss">
.event-setting-flow {
  .other-setting-panel { 
    .other-setting-main {
      .trigger-list-setting-header {
        padding-left: 10px;
      }
    }
  }
}
</style>
